<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 15/11/17
 * Time: 下午3:00
 */
$api_service_path = __DIR__ . "/../../../api/";
ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();

$cars = DB::table('jd_car_data')->where('id','>','20453')
    ->select('id','car_model_id')
    ->get();
foreach($cars as $_car){
    $_maintain = getMaintain($_car->car_model_id);
    if($_maintain->code == 'success'){
        $maintainInfo = $_maintain->data->maintainInfo;
        $columnCells = $maintainInfo->columnCells;
        foreach($columnCells as $_cells){
            if($_cells->num == 0){
                $items = $_cells->cells;
                foreach($items as $_item){
                    $jd_car_maintenance = array(
                        'jd_car_id' => $_car->id,
                        'car_model_id' => $_car->car_model_id,
                        'title' => $maintainInfo->title,
                        'comment' => $maintainInfo->titleComment,
                        'item' => $_item
                    );
                    try{
                        DB::table('jd_car_maintenance')->insert($jd_car_maintenance);
                    }catch (Exception $e) {
                        echo "insert into jd_car_maintenance error\n";
                        var_dump($e);
                    }
                }
            }else{
                $jd_car_maintenance_handbook = array(
                    'jd_car_id' => $_car->id,
                    'car_model_id' => $_car->car_model_id,
                    'mile' => $_cells->columnName,
                    'maintain' => json_encode($_cells->cells)
                );
                try{
                    DB::table('jd_car_maintenance_handbook')->insert($jd_car_maintenance_handbook);
                }catch (Exception $e) {
                    echo "insert into jd_car_maintenance_handbook error\n";
                    var_dump($e);
                }
            }
        }
    }else{
        echo $_car->id . ' ' . $_maintain->code . ' ' . $_maintain->result . ' ' . $_maintain->data . "\n";
        $jd_car_maintenance = array(
            'jd_car_id' => $_car->id,
            'car_model_id' => $_car->car_model_id,
            'title' => $_maintain->code,
            'comment' => $_maintain->result,
            'item' => $_maintain->data
        );
        try{
            DB::table('jd_car_maintenance')->insert($jd_car_maintenance);
        }catch (Exception $e) {
            echo "insert into jd_car_maintenance error\n";
            var_dump($e);
        }
    }
    usleep(500);
}

function getMaintain($car_model_id){

    $url = 'http://auto.jd.com/maintain/getMaintain?carModelId='.$car_model_id.'&mileage=1';
    $response = Httpful::get($url)
        ->timeoutIn(5)
        ->sendsForm()->send();
    return $response->body;
}